const path = require('path')
const fs = require('fs')
function keyword(message,keywords){
  let keyword=keywords.find(function(value){
    return message.indexOf(value)==0;
  });
  if(keyword){
    return {
      hasKeyWord:true,
      keyword,
      message:message.replace(keyword,"").trim()
    }
  }else{
    return {
      hasKeyWord:false,
      message
    }
  }
}
function loadPlugin(filePath){
  let files = fs.readdirSync(filePath)
  let list=[]
  for (let i = 0; i < files.length; i++) {
    let fileName = files[i]
    let fileDir = path.join(filePath, fileName)
    if (fileName !== 'index.js') {
      console.log('加载插件'+fileName+"成功")
      let temp = require(fileDir)// 载入所有插件
      let func= temp['plugin']
      list.push(func)
    }
  }
  return list
}
// 辅助函数
function chainablize(constructor) {
  let prototype = constructor.prototype;
  for(let method in prototype) {
    try {
      if(prototype.hasOwnProperty(method) && typeof prototype[method] == 'function') {
        (function(method) {
          let old = prototype[method];
          prototype[method] = function() {
            let result = old.apply(this, arguments);
            return result === void 0 ? this : result;
          };
        })(method);
      }
    } catch(e) {}
  }

  if('prop' in prototype) return;
  prototype.prop = function(object) {
    for(let property in object) {
      this[property] = object[property];
    }
    return this;
  }
}
function checkExist(params,key,value){
  return params[key]==value;
}
function saveToFile(filePath,value){
  fs.writeFile(path.join(__dirname,filePath),JSON.stringify(value),(err)=>{
    console.error(err)
  })
}
module.exports= {
  chainablize,
  loadPlugin,
  saveToFile,
  keyword,
  checkExist
};
